<template>
  <!-- 查询医生 -->
  <el-select v-model="curData" @change="onChange" value-key="id" filterable remote :remote-method="onSearch" clearable @clear="onClear" placeholder="请选择医生" style="width:100%">
    <el-option v-for="(item,index) in tableList" :key="index" :label="item.trueName" :value="item"></el-option>
    <br>
    <pager v-model="pager" small @change-pagenum="getData"></pager>
  </el-select>
</template>
<script>
export default {
  props: ["value", "deptId"],
  data() {
    return {
      curData: null,
      queryStr: "",
      pager: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      tableList: []
    };
  },
  mounted() {
    const th = this;
    if (th.value) th.getById();
    else th.onSearch();
  },
  methods: {
    onSearch(name) {
      const th = this;
      th.queryStr = name;
      th.pager.pageNum = 1;
      th.getData(-1);
    },
    onChange() {
      const th = this;
      th.$emit("change", th.curData);
      if (th.curData) {
        th.$emit("input", th.curData.id);
      } else {
        th.$emit("input", null);
      }
    },
    getData(type) {
      const th = this;
      if (type == -1) {
        th.pager.total = 0;
        th.pager.pageNum = 1;
      }
      let j = {
        hpId: th.adminUser.hpId,
        deptId: th.deptId,
        doctorName: th.queryStr,
        status: 1
      };
      Object.assign(j, th.pager);
      th.$api.getDoctorPageList(j).then(res => {
        if (res.executed) {
          th.tableList = res.dataBody.list;
          th.pager.total = res.dataBody.total;
        }
      });
    },
    getById(id) {
      const th = this;
      let j = {
        doctorId: id || th.value,
        hpId: th.adminUser.hpId,
        deptId: th.deptId
      };
      // th.$api.getDoctorById(j).then(res => {
      //   th.tableList = [res.dataBody];
      //   th.pager.total = 1;
      //   th.pager.pageNum = 1;
      //   th.curData = res.dataBody;
      // });
      th.$api.getDoctorPageList(j).then(res => {
        if (res.executed) {
          th.tableList = res.dataBody.list;
          th.pager.total = res.dataBody.total;
          th.curData = res.dataBody.list[0];
        }
      });
    },
    onClear() {
      const th = this;
      th.onSearch();
    }
  },
  watch: {
    value: {
      deep: true,
      handler(n) {
        const th = this;
        if (n) {
          let data = th.tableList.find(d => {
            return d.id == n;
          });
          if (data) {
            th.curData = data;
          } else {
            th.getById();
          }
        } else {
          th.curData = null;
        }
      }
    }
  }
};
</script>